package com.wanban.downloader.http

import com.wanban.downloader.exception.HttpConnectionException
import com.wanban.downloader.model.DownloadParams
import com.wanban.downloader.utils.Constants
import com.wanban.downloader.utils.ErrorMessage
import com.wanban.downloader.utils.OkHttpClientProvider
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.closeQuietly
import java.io.IOException
import java.io.InterruptedIOException
import java.util.concurrent.TimeUnit
class HttpConnectUtils {


    private var interrupted = false
    private var call: Call? = null

    fun open(uri: String, httpHeaders: Map<String, String?>? = null): Response? {
        var response: Response? = null
        try {
            val builder = Request.Builder()
            builder.url(uri)
            httpHeaders?.keys?.forEach {
                val key = it
                val value = httpHeaders[key].toString()
                builder.addHeader(key, value)
            }
            val request = builder.build()
            if (interrupted) return null
            call = OkHttpClientProvider.getOkHttpClient().newCall(request)
            response = call?.execute()?: throw HttpConnectionException("下载出错，视频地址无法访问，CODE:01！")
            if (!response.isSuccessful) {
                response.closeQuietly()
                if (interrupted) return null
                throw HttpConnectionException("下载出错，视频地址无法访问，CODE:02！")
            }
            val responseCode = response.code
            // Check for a valid response code.
            if (responseCode < 200 || responseCode > 299) {
                response.closeQuietly()
                if (interrupted) return null
                throw HttpConnectionException("下载出错，视频地址无法访问，CODE:03！")
            }
            val responseBody = response.body
            if (responseBody == null) {
                response.closeQuietly()
                if (interrupted) return null
                throw HttpConnectionException("下载出错，视频地址无法访问，CODE:04！")
            }
            if (interrupted) return null
            return response
        } catch (e: IOException) {
            response?.closeQuietly()
            if (e is InterruptedIOException || interrupted) return null
            throw HttpConnectionException("下载出错，视频地址无法访问，CODE:05！")
        }
    }

    fun close() {
        interrupted = true
        if (call != null && call?.isCanceled() == false) {
            call?.cancel()
        }
    }
}